<?php
namespace App\Api\Controllers\AlipayOpen;


use Alipayopen\Sdk\AopClient;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Api\Controllers\Push\JpushController;
use App\Common\MerchantFuwu;
use App\Common\PaySuccessAction;
use App\Common\UserHbfqGetMoney;
use App\Common\StoreDayMonthOrder;
use App\Common\UserGetMoney;
use App\Http\Controllers\Controller;
use App\Models\AlipayAppOauthUsers;
use App\Models\AlipayHbOrder;
use App\Models\AlipayZftStore;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class NotifyController extends \App\Api\Controllers\BaseController
{

    //官方支付宝处理
    public function qr_pay_notify(Request $request)
    {
        try {
            //支付异步通知
            $data = $request->all();

            $day = date('Ymd', time());
            $table = 'orders_' . $day;
            if (Schema::hasTable($table)) {
                $Order = DB::table($table)->where('out_trade_no', $data['out_trade_no'])->first();
            } else {
                $Order = Order::where('out_trade_no', $data['out_trade_no'])->first();
            }

            $store_id = $Order->store_id;

            $store = Store::where('store_id', $Order->store_id)
                ->select('pid', 'config_id')
                ->first();
            $store_pid = $store->pid;
            //配置
            $isvconfig = new AlipayIsvConfigController();

            $config_type = '01';
            $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid); //通道信息
            if ($storeInfo->config_type == '02') {
                $config_type = '02';
            }

            $config = $isvconfig->AlipayIsvConfig($store->config_id, $config_type);
            if ($config) {
                //1.接入参数初始化
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2";//升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "UTF-8";

                $check = $aop->rsaCheckUmxnt($request->all(), $config->alipay_rsa_public_key);
                if ($check) {
                    //如果状态不相同修改数据库状态
                    if ($Order->status != $data['trade_status']) {
                        if ($data['trade_status'] == 'TRADE_SUCCESS') {
                            if ($Order->pay_status != 1) {
                                $payment_method = json_decode($data['fund_bill_list'], true)[0]['fundChannel'];

                                $type = 1003;
                                $updatedata = [
                                    'status' => $data['trade_status'],
                                    'payment_method' => $payment_method,
                                    'buyer_id' => $data['buyer_id'],
                                    'buyer_logon_id' => $data['buyer_logon_id'],
                                    'trade_no' => $data['trade_no'],
                                    'total_amount' => $data['total_amount'],
                                    'receipt_amount' => $data['receipt_amount'],
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                ];
                                $this->update_day_order($updatedata, $data['out_trade_no']);

                                if (strpos($data['out_trade_no'], 'scan')) {

                                } else {
                                    //支付成功后的动作
                                    $data = [
                                        'ways_type' => '1000',
                                        'company' => $Order->company,
                                        'ways_type_desc' => '支付宝',
                                        'source_type' => '1000',//返佣来源
                                        'source_desc' => '支付宝',//返佣来源说明
                                        'total_amount' => $Order->total_amount,
                                        'out_trade_no' => $Order->out_trade_no,
                                        'other_no' => $Order->other_no,
                                        'rate' => $Order->rate,
                                        'fee_amount' => $Order->fee_amount,
                                        'merchant_id' => $Order->merchant_id,
                                        'store_id' => $Order->store_id,
                                        'user_id' => $Order->user_id,
                                        'config_id' => $store->config_id,
                                        'store_name' => $Order->store_name,
                                        'remark' => $Order->remark,
                                        'ways_source' => $Order->ways_source,
                                        'device_id' => $Order->device_id,
                                    ];
                                    PaySuccessAction::action($data);
                                }
                            }
                        }
                    }
                }
            }

            echo 'success';
        } catch (\Exception $ex) {
            Log::info('支付宝交易异步-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //官方支付宝分期处理
    public function fq_pay_notify(Request $request)
    {
        try {
            //支付异步通知
            $data = $request->all();

            $Order = AlipayHbOrder::where('out_trade_no', $data['out_trade_no'])->first();
            $store_id = $Order->store_id;

            $store = Store::where('store_id', $Order->store_id)
                ->select('pid', 'config_id')
                ->first();
            $store_pid = $store->pid;
            //配置
            $isvconfig = new AlipayIsvConfigController();

            $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid);//通道信息
            $app_auth_token = $storeInfo->app_auth_token;

            $config_type = '01';
            $config = $isvconfig->AlipayIsvConfig($Order->config_id, $config_type);
            if ($config) {
                //1.接入参数初始化
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2";//升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "UTF-8";

                $check = $aop->rsaCheckUmxnt($request->all(), $config->alipay_rsa_public_key);
                if ($check) {
                    //如果状态不相同修改数据库状态
                    if ($Order->status != $data['trade_status']) {
                        if ($data['trade_status'] == 'TRADE_SUCCESS') {
                            //改变数据库
                            if ($Order->pay_status != 1) {
                                $updatedata = [
                                    'buyer_id' => $data['buyer_id'],
                                    'buyer_logon_id' => $data['buyer_logon_id'],
                                    'trade_no' => $data['trade_no'],
                                    'total_amount' => $data['total_amount'],
                                    'receipt_amount' => $data['receipt_amount'],
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                ];
                                AlipayHbOrder::where('out_trade_no', $data['out_trade_no'])->update($updatedata);

                                if (strpos($data['out_trade_no'], 'scan')) {

                                } else {
                                    //支付成功后的动作
                                    $action_data = [
                                        'ways_type' => '1000',
                                        'company' => $Order->company,
                                        'ways_type_desc' => '支付宝',
                                        'source_type' => '1000',//返佣来源
                                        'source_desc' => '支付宝',//返佣来源说明
                                        'total_amount' => $Order->total_amount,
                                        'out_trade_no' => $Order->out_trade_no,
                                        'other_no' => $Order->other_no,
                                        'rate' => $Order->rate,
                                        'fee_amount' => $Order->fee_amount,
                                        'merchant_id' => $Order->merchant_id,
                                        'store_id' => $Order->store_id,
                                        'user_id' => $Order->user_id,
                                        'config_id' => $Order->config_id,
                                        'store_name' => $Order->store_name,
                                        'remark' => $Order->remark,
                                        'ways_source' => $Order->ways_source,
                                        'device_id' => $Order->device_id,
                                        'no_user_money' => '1',//不计算返佣
                                    ];
                                    PaySuccessAction::action($action_data);
                                }
                            }

                            //服务商返佣入库
                            $UserGetMoney = [
                                'config_id' => $Order->config_id,//服务商ID
                                'user_id' => $Order->user_id,//直属代理商
                                'store_id' => $Order->store_id,//门店
                                'out_trade_no' => $Order->out_trade_no,//订单号
                                'ways_type' => $Order->ways_type,//通道类型
                                'order_total_amount' => $Order->total_amount,//交易金额
                                'store_ways_type_rate' => $Order->xy_rate,//交易时的费率
                                'source_type' => '1001',//返佣来源
                                'source_desc' => '花呗分期',//返佣来源说明
                                'num' => $Order->hb_fq_num,//返佣来源说明
                                'merchant_id' => $Order->merchant_id,//返佣来源说明
                                'merchant_name' => $Order->merchant_name,//返佣来源说明
                                'store_name' => $Order->store_name,//返佣来源说明
                            ];

                            $obj = new  UserHbfqGetMoney($UserGetMoney);
                            $obj->insert();
                        }
                    }

                    //分成
                    if ($data['trade_status'] == 'TRADE_SUCCESS') {
                        //转出
                        $day = date('Ymd', time());
                        $table = 'settle_orders_' . $day;
                        $obj = DB::table($table);
                        $settle_orders = $obj->where('out_trade_no', $data['out_trade_no'])
                            ->select('status', 'order_settle_amount')
                            ->first();
                        if ($settle_orders && $settle_orders->status != 1) {
                            $order_settle_amount = number_format($settle_orders->order_settle_amount, 2, '.', '');//当面付费率
                            $data = [
                                'out_request_no' => $Order->out_trade_no . '11',
                                'trade_no' => $data['trade_no'],
                                'config' => $config,
                                'order_settle_amount' => $order_settle_amount
                            ];

                            $obj = new \App\Api\Controllers\AlipayOpen\PayController();
                            $zft_order_settle = $obj->zft_order_settle($data, $app_auth_token);

                            $updatedata = [
                                'trade_no' => $data['trade_no'],
                                'status' => $zft_order_settle['status'],
                                'status_desc' => $zft_order_settle['message'],
                            ];
                            $this->update_settle_order($updatedata, $Order->out_trade_no);
                        }
                    }
                }
            }

            echo 'success';
        } catch (\Exception $ex) {
            Log::info('花呗分期异步-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //直付通支付宝处理
    public function zft_qr_pay_notify(Request $request)
    {
        try {
            //支付异步通知
            $data = $request->all();
            $day = date('Ymd', time());
            $table = 'orders_' . $day;
            if (Schema::hasTable($table)) {
                $Order = DB::table($table)->where('out_trade_no', $data['out_trade_no'])->first();
            } else {
                $Order = Order::where('out_trade_no', $data['out_trade_no'])->first();
            }

            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config_type = '03';
            $config = $isvconfig->AlipayIsvConfig($Order->config_id, $config_type);
            if ($config) {
                //1.接入参数初始化
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2";//升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "UTF-8";

                $check = $aop->rsaCheckUmxnt($request->all(), $config->alipay_rsa_public_key);
                if ($check) {
                    //如果状态不相同修改数据库状态
                    if ($Order->status != $data['trade_status']) {
                        if ($data['trade_status'] == 'TRADE_SUCCESS') {
                            if ($Order->pay_status != 1) {
                                $payment_method = json_decode($data['fund_bill_list'], true)[0]['fundChannel'];

                                $updatedata = [
                                    'status' => $data['trade_status'],
                                    'payment_method' => $payment_method,
                                    'buyer_id' => $data['buyer_id'],
                                    'buyer_logon_id' => $data['buyer_logon_id'],
                                    'trade_no' => $data['trade_no'],
                                    'total_amount' => $data['total_amount'],
                                    'receipt_amount' => $data['receipt_amount'],
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                ];
                                $this->update_day_order($updatedata, $data['out_trade_no']);
                            }

                            if ($Order->pay_method == 'qr_code') {
                                //支付成功后的动作
                                $data_in = [
                                    'ways_type' => $Order->ways_type,
                                    'company' => $Order->company,
                                    'ways_type_desc' => '支付宝',
                                    'source_type' => '16000',//返佣来源
                                    'source_desc' => 'ZFT',//返佣来源说明
                                    'total_amount' => $Order->total_amount,
                                    'out_trade_no' => $Order->out_trade_no,
                                    'other_no' => $Order->other_no,
                                    'rate' => $Order->rate,
                                    'fee_amount' => $Order->fee_amount,
                                    'merchant_id' => $Order->merchant_id,
                                    'store_id' => $Order->store_id,
                                    'user_id' => $Order->user_id,
                                    'config_id' => $Order->config_id,
                                    'store_name' => $Order->store_name,
                                    'remark' => $Order->remark,
                                    'ways_source' => $Order->ways_source,
                                    'device_id' => $Order->device_id,
                                ];
                                PaySuccessAction::action($data_in);
                            }
                        }
                    }

                    //分成入库
                    if ($data['trade_status'] == 'TRADE_SUCCESS') {
                        //如果存在base
                        if (Schema::hasTable('settle_order_base')) {
                            //分成比例调转
                            $rate = $Order->rate;
                            $UserRate = UserRate::where('user_id', '1')
                                ->where('company', $Order->company)
                                ->where('ways_type', $Order->ways_type)
                                ->select('rate')
                                ->first();
                            if ($UserRate && $rate > $UserRate->rate) {
                                //配置
                                $order_settle_amount = ($rate - $UserRate->rate) * $Order->total_amount / 100;
                                $order_settle_amount = number_format($order_settle_amount, 2, '.', '');//当面付费率
                                if ($order_settle_amount > 0) {
                                    $data = [
                                        'out_request_no' => $Order->out_trade_no . '11',
                                        'trade_no' => $data['trade_no'],
                                        'config' => $config,
                                        'order_settle_amount' => $order_settle_amount
                                    ];

                                    $obj = new \App\Api\Controllers\AlipayOpen\PayController();
                                    $zft_order_settle = $obj->zft_order_settle($data);

                                    $updatedata = [
                                        'trade_no' => $data['trade_no'],
                                        'config_id' => $Order->config_id,
                                        'order_settle_amount' => $order_settle_amount,
                                        'store_id' => $Order->store_id,
                                        'trans_out' => $config->alipay_pid,
                                        'user_id' => $Order->user_id,
                                        'out_trade_no' => $Order->out_trade_no,
                                        'total_amount' => $Order->total_amount,
                                        'status' => $zft_order_settle['status'],
                                        'status_desc' => $zft_order_settle['message'],
                                    ];
                                    $this->insert_settle_order($updatedata);
                                }
                            }
                        }
                    }
                }
            }

            echo 'success';
        } catch (\Exception $ex) {
            Log::info('直付通支付宝异步-错误');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //直付通花呗分期处理
    public function zft_fq_pay_notify(Request $request)
    {
        try {
            //支付异步通知
            $data = $request->all();
            $Order = AlipayHbOrder::where('out_trade_no', $data['out_trade_no'])->first();
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config_type = '03';
            $config = $isvconfig->AlipayIsvConfig($Order->config_id, $config_type);
            if ($config) {
                //1.接入参数初始化
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2";//升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "UTF-8";

                $check = $aop->rsaCheckUmxnt($request->all(), $config->alipay_rsa_public_key);
                if ($check) {
                    //如果状态不相同修改数据库状态
                    if ($Order->status != $data['trade_status']) {

                        if ($data['trade_status'] == 'TRADE_SUCCESS') {
                            if ($Order->pay_status != 1) {
                                $updatedata = [
                                    'buyer_id' => $data['buyer_id'],
                                    'buyer_logon_id' => $data['buyer_logon_id'],
                                    'trade_no' => $data['trade_no'],
                                    'total_amount' => $data['total_amount'],
                                    'receipt_amount' => $data['receipt_amount'],
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                ];

                                AlipayHbOrder::where('out_trade_no', $data['out_trade_no'])
                                    ->update($updatedata);

                                //支付成功后的动作
                                $action_data = [
                                    'ways_type' => '16002',
                                    'company' => $Order->company,
                                    'ways_type_desc' => '支付宝',
                                    'source_type' => '16000',//返佣来源
                                    'source_desc' => '支付宝-zft',//返佣来源说明
                                    'total_amount' => $Order->total_amount,
                                    'out_trade_no' => $Order->out_trade_no,
                                    'other_no' => $Order->other_no,
                                    'rate' => $Order->rate,
                                    'fee_amount' => $Order->fee_amount,
                                    'merchant_id' => $Order->merchant_id,
                                    'store_id' => $Order->store_id,
                                    'user_id' => $Order->user_id,
                                    'config_id' => $Order->config_id,
                                    'store_name' => $Order->store_name,
                                    'remark' => $Order->remark,
                                    'ways_source' => $Order->ways_source,
                                    'device_id' => $Order->device_id,
                                    'no_user_money' => '1',//不计算返佣
                                ];
                                PaySuccessAction::action($action_data);
                            }

                            //服务商返佣入库
                            $UserGetMoney = [
                                'config_id' => $Order->config_id,//服务商ID
                                'user_id' => $Order->user_id,//直属代理商
                                'store_id' => $Order->store_id,//门店
                                'out_trade_no' => $Order->out_trade_no,//订单号
                                'ways_type' => $Order->ways_type,//通道类型
                                'order_total_amount' => $Order->total_amount,//交易金额
                                'store_ways_type_rate' => $Order->xy_rate,//交易时的费率
                                'source_type' => '16001',//返佣来源
                                'source_desc' => '花呗分期-ZFT',//返佣来源说明
                                'num' => $Order->hb_fq_num,//返佣来源说明
                                'merchant_id' => $Order->merchant_id,//返佣来源说明
                                'merchant_name' => $Order->merchant_name,//返佣来源说明
                                'store_name' => $Order->store_name,//返佣来源说明
                            ];

                            $obj = new  UserHbfqGetMoney($UserGetMoney);
                            $obj->insert();
                        }
                    }

                    //转出
                    if ($data['trade_status'] == 'TRADE_SUCCESS') {
                        //转出
                        $day = date('Ymd', time());
                        $table = 'settle_orders_' . $day;
                        $obj = DB::table($table);
                        $settle_orders = $obj->where('out_trade_no', $data['out_trade_no'])
                            ->select('status', 'order_settle_amount')
                            ->first();
                        if ($settle_orders && $settle_orders->status != 1) {
                            $order_settle_amount = number_format($settle_orders->order_settle_amount, 2, '.', '');//当面付费率
                            $data = [
                                'out_request_no' => $Order->out_trade_no . '11',
                                'trade_no' => $data['trade_no'],
                                'config' => $config,
                                'order_settle_amount' => $order_settle_amount
                            ];

                            $obj = new \App\Api\Controllers\AlipayOpen\PayController();
                            $zft_order_settle = $obj->zft_order_settle($data);

                            $updatedata = [
                                'trade_no' => $data['trade_no'],
                                'status' => $zft_order_settle['status'],
                                'status_desc' => $zft_order_settle['message'],
                            ];
                            $this->update_settle_order($updatedata, $Order->out_trade_no);
                        }
                    }
                }
            }

            echo 'success';
        } catch (\Exception $ex) {
            Log::info('花呗分期异步-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //
    public function gateway(Request $request)
    {
        try {
            $abc = $request->all();
            $biz_content = json_decode($abc['biz_content'], true);
            $external_id = $biz_content['external_id'];
            $order_id = $biz_content['order_id'];

            $AlipayZftStore = AlipayZftStore::where('store_id', $external_id)
                ->where('order_id', $order_id)
                ->first();

            if (!$AlipayZftStore) {
                return 'success';
            }
            $config_id = $AlipayZftStore->config_id;
            $store_id = $AlipayZftStore->store_id;
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config_type = '03';//直付通
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

            if (!$config) {
                return 'success';
            }

            //1.接入参数初始化
            $aop = new AopClient();
            $aop->apiVersion = "2.0";
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->signType = "RSA2";//升级算法
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->format = "json";
            $aop->charset = "UTF-8";

            $check = $aop->rsaCheckUmxnt($request->all(), $config->alipay_rsa_public_key);

            //验证是否是支付宝发送
            if ($check) {
                $msg_method = $abc['msg_method'];

                //成功
                if ($msg_method == "ant.merchant.expand.indirect.zft.passed") {
                    $AlipayZftStore->status = "99";
                    $AlipayZftStore->ext_info = $abc['biz_content'];
                    $biz_content = json_decode($abc['biz_content'], true);
                    $smid = $biz_content['smid'];
                    $AlipayZftStore->smid = $smid;
                    $AlipayZftStore->card_alias_no = isset($biz_content['card_alias_no']) ? $biz_content['card_alias_no'] : "";
                    $AlipayZftStore->save();
                    $status_desc = $biz_content['memo'];
                    $data_up = [
                        'status' => 1,
                        'status_desc' => $status_desc,
                        'pcredit'=>'01',
                        'credit'=>"00",
                    ];

                } else {
                    $AlipayZftStore->status = "-1";
                    $AlipayZftStore->save();
                    $status_desc = $biz_content['reason'];

                    $data_up = [
                        'status' => 3,
                        'status_desc' => $status_desc,
                        'pcredit'=>'01',
                        'credit'=>"00",
                    ];
                }

                StorePayWay::where('store_id', $store_id)
                    ->where('company', 'zft')
                    ->update($data_up);

                return 'success';
            } else {
                return 'fail';
            }
        } catch (\Exception $ex) {
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return 'fail';
        }
    }


}

